package com.fh.tags;

import com.fh.util.Const;
import com.fh.util.UserUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.tags.RoleTag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * 创建者：shanlin
 * 创建时间：2017/9/27 13:24
 **/
public class ShiroTag extends RoleTag {
    private Logger logger = LoggerFactory.getLogger(ShiroTag.class);

    private String role;
    private String qx;

    public String getRole() {
        return role;
    }

    public void setRole(String role) {
        this.role = role;
    }

    public String getQx() {
        return qx;
    }

    public void setQx(String qx) {
        this.qx = qx;
    }

    @Override
    protected boolean showTagBody(String s) {
        boolean flag = false;
        Map<String, String> shiroMap = getQX();
        String qxStr = this.getQx();
        if(qxStr == null) return flag;
        String[] qxArr = qxStr.split(":");
        if (shiroMap.containsKey("role") && shiroMap.containsKey(qxArr[0])) {
            boolean condition;
            if(this.getRole() != null) {//指定了角色和对应权限
                //判断角色权限
                 condition = (this.getRole().equals(shiroMap.get("role")) && qxArr[1].equals(shiroMap.get(qxArr[0])))
                        || "管理员".equals(shiroMap.get("role"));
                if (condition) {
                    flag = true;
                }
            }else{//不指定角色
                condition = qxArr[1].equals(shiroMap.get(qxArr[0])) || "管理员".equals(shiroMap.get("role"));
                if (condition) {
                    flag = true;
                }
            }
        }
        return flag;
    }


    private Map<String, String> getQX() {
        Map<String, String> map = getHC();
        String roleId = UserUtils.getUser().getRole().getROLE_ID();
        String role = "管理员";
        if (Const.ROLE_CSZZ.equals(roleId)) {
            role = "催收组长";
        }
        if (Const.ROLE_CSJL.equals(roleId)) {
            role = "催收经理";
        }
        if (Const.ROLE_CSY.equals(roleId)) {
            role = "催收专员";
        }
        if (Const.ROLE_WWGS.equals(roleId)) {
            role = "委外公司";
        }
        if (Const.ROLE_WWZY.equals(roleId)) {
            role = "委外专员";
        }
        map.put("role", role);
        logger.info("执行自定义标签获取角色权限：" + map);
        return map;
    }

    public Map<String, String> getHC() {
        Subject currentUser = SecurityUtils.getSubject();  //shiro管理的session
        Session session = currentUser.getSession();
        return (Map<String, String>) session.getAttribute(Const.SESSION_QX);
    }
}
